package servlets;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cmput391.src.queries.*;

/**
 * Servlet implementation class DeleteUser
 */
@WebServlet("/AddDoctor")
public class AddDoctor extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddDoctor() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String> messages = new HashMap<String, String>();
		request.setAttribute("messages", messages);		

		String username = (request.getParameter("username")).trim();
		String doctor = (request.getParameter("doctor")).trim();
			
		DBConnector dbConnect = new DBConnector();
		SecurityQueries security = null;
		
		try {
			security = new SecurityQueries(dbConnect.getConnection());
			UserManagementQueries umq = new UserManagementQueries(dbConnect.getConnection(), security);
			umq.addDoctorToPatient(username, doctor);
			messages.put("add_doctor_msg", "<span class=\"message success\">Doctor Added.</span>");

			request.getRequestDispatcher("EditForm?user_name="+username).include(request,response);
			return;
		}
		catch (com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException e) {
			messages.put("add_doctor_msg", "<span class=\"message error\">The patient already sees this doctor.</span>");
			request.getRequestDispatcher("EditForm?user_name="+username).include(request,response);			
		}
		catch (Exception e) {
			//response.sendError(500);
			request.getRequestDispatcher("EditForm?user_name="+username).forward(request, response);				
		    e.printStackTrace();
		    return;
		}
	}

}
